package com.nwpu.am.service.impl;

import com.nwpu.am.constant.properties.ShiroProperties;
import com.nwpu.am.mapper.UserMapper;
import com.nwpu.am.pojo.dto.UserAddDTO;
import com.nwpu.am.pojo.entity.User;
import com.nwpu.am.service.UserService;
import com.nwpu.am.utils.id_generator.IdGenerator;
import com.nwpu.am.utils.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * UserServiceImpl
 *
 * @author Roy
 * @version 1.0
 * {@code @date} 2024/6/3
 */

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private ShiroProperties shiroProperties;
    @Resource
    private IdGenerator idGenerator;

    @Override
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    @Override
    public void addUser(UserAddDTO userAddDTO) {
        User user = userAddDTO.toUser();
        // md5加密
        ByteSource salt = ByteSource.Util.bytes(shiroProperties.getSalt());
        String encryptedPassword = MD5Util.getMD5AsHexWithSalt(userAddDTO.getPassword(), salt, shiroProperties.getHashIterations());

        user.setPassword(encryptedPassword);
        // 设置ID
        long userId = idGenerator.nextId();
        user.setUserId(userId);

        userMapper.insertUser(user);
    }
}
